<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  canvas {
    background: #ccc;
  }
</style>

<body>
  <canvas id="myCanvas" width="500" height="500"></canvas>
  <script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");
    let startX, startY;

    canvas.addEventListener("mousedown", function (event) {
      // 记录起点坐标
      startX = event.clientX - canvas.offsetLeft;
      startY = event.clientY - canvas.offsetTop;

      // 设置线条样式
      ctx.strokeStyle = "black";
      ctx.lineWidth = 2;
    });

    canvas.addEventListener("mousemove", function (event) {
      if (startX && startY) { // 如果已经有了起点坐标
        // 清空 Canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制之前的箭头画笔
        drawArrow(startX, startY, event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop, 10);
      }
    });

    canvas.addEventListener("mouseup", function (event) {
      if (startX && startY) { // 如果已经有了起点坐标
        // 绘制最终的箭头画笔
        drawArrow(startX, startY, event.clientX - canvas.offsetLeft, event.clientY - canvas.offsetTop, 10);

        // 清空起点坐标
        startX = null;
        startY = null;
      }
    });
    function drawArrow (startX, startY, endX, endY, arrowSize) {
      // 设置线条样式和颜色
      ctx.strokeStyle = "red";
      ctx.lineWidth = 2;
      // 绘制直线
      ctx.beginPath();
      ctx.moveTo(startX, startY);
      ctx.lineTo(endX, endY);
      ctx.stroke();

      // 计算箭头角度和长度
      const angle = Math.atan2(endY - startY, endX - startX);
      const arrowLength = Math.sqrt(Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2));

      // 绘制箭头
      ctx.save();
      ctx.translate(endX, endY);
      ctx.rotate(angle);

      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(-arrowLength / arrowSize, arrowLength / (2 * arrowSize));
      ctx.lineTo(-arrowLength / arrowSize, -arrowLength / (2 * arrowSize));
      ctx.closePath();
      ctx.fillStyle = "red"; // 箭头颜色
      ctx.fill();

      ctx.restore();
    }


  </script>
</body>

</html>